package com.richbond.sdjdsm.fragments;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.richbond.sdjdsm.AboutActivity;
import com.richbond.sdjdsm.R;
import com.richbond.sdjdsm.bean.UpdateBean;
import com.richbond.sdjdsm.common.BaseFragment;
import com.richbond.sdjdsm.util.DialogHelper;
import com.richbond.sdjdsm.util.JsonUtil;
import com.richbond.sdjdsm.util.UIHelp;
import com.richbond.sdjdsm.util.clear.ClearCache;
import com.richbond.sdjdsm.util.clear.GetFileSize;
import com.richbond.sdjdsm.util.update.UpdateManager;
import com.richbond.sdjdsm.webserver.PoiWS;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * Created by liwenxun on 15/9/1.
 */
public class SettingFragment extends BaseFragment {

    private LinearLayout  llClear, llRefresh, llAbout;
    private PoiWS ws;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = setBaseContentLayout(R.layout.fragment_setting);

        init(view);
        ws = new PoiWS(getActivity());
    }


    private void init(View v) {

        llClear = (LinearLayout) v.findViewById(R.id.llClear);
        llRefresh = (LinearLayout) v.findViewById(R.id.llRefresh);
        llAbout = (LinearLayout) v.findViewById(R.id.llAbout);

        llClear.setOnClickListener(clickListener);
        llRefresh.setOnClickListener(clickListener);
        llAbout.setOnClickListener(clickListener);


    }

    View.OnClickListener clickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
           if (v.getId() == R.id.llClear) {
                clearCache();
            } else if (v.getId() == R.id.llRefresh) {
                if (UIHelp.isNetworkConnected(getActivity())) {
                    new UpdateTask().execute();
                } else {
                    DialogHelper.showToast(getActivity(), "请检查你到网络");
                }
            } else if (v.getId() == R.id.llAbout) {
                startActivity(new Intent(getActivity(), AboutActivity.class));
            }
        }
    };

    //获得缓存大小的方法
    private String getCacheSize() {
        String size = "";
        long l = 0;
        GetFileSize g = new GetFileSize();
        l = g.getCacheSize(getActivity().getCacheDir())
                + g.getCacheSize(new File("/data/data/" + getActivity().getPackageName() + "/databases"))
                + g.getCacheSize(new File("/data/data/" + getActivity().getPackageName() + "/shared_prefs"))
                + g.getCacheSize(getActivity().getFilesDir());
        size = g.FormetFileSize(l);
        return size;
    }

    //清除的方法 去工具类调用几个删除的方法
    private void doClear() {
        //清除本应用内部缓存(/data/data/com.xxx.xxx/cache)
        ClearCache.cleanInternalCache(getActivity());

        //清除本应用所有数据库(/data/data/com.xxx.xxx/cache)
        ClearCache.cleanDatabases(getActivity());

        //清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs)
        ClearCache.cleanSharedPreference(getActivity());
        /*
        //按名字清除本应用数据库
        ClearCache.cleanDatabaseByName(getActivity(),"数据库名称");
        */

        //清除/data/data/com.xxx.xxx/files下的内容
        ClearCache.cleanFiles(getActivity());

        //清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache)
        ClearCache.cleanExternalCache(getActivity());


    }


    //清理缓存
    private void clearCache() {

        String size = getCacheSize();
        final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_base1);
        TextView tvTitle = (TextView) window.findViewById(R.id.tvTitle);
        Button btnLeft = (Button) window.findViewById(R.id.btnLeft);
        Button btnRight = (Button) window.findViewById(R.id.btnRight);
        tvTitle.setText(getString(R.string.is_delete) + "\n" + "（缓存大小：" + size + "）");

        btnLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 删除文件
                doClear();
                DialogHelper.showToast(getActivity(), getString(R.string.clearDone));
                alertDialog.dismiss();
            }
        });

        btnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }

    /**
     * 获取更新的异步任务
     */
    private class UpdateTask extends AsyncTask<String, String, JSONObject> {
        @Override
        protected JSONObject doInBackground(String... params) {
            return ws.Update();
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            super.onPostExecute(result);
            DialogHelper.closeProgressDialog();
            Log.v("获取更新的json---result=======", String.valueOf(result));
            if (JsonUtil.GetJsonStatu(result)) {
                final UpdateBean updateBean = new UpdateBean();
                try {
                    JSONObject jsonObject = result.getJSONObject("data");
                    updateBean.setAppVersionCode(jsonObject.getString("appVersionCode"));
                    updateBean.setAppVersionName(jsonObject.getString("appVersionName"));
                    updateBean.setAppDownloadUrl(jsonObject.getString("appDownloadUrl"));
                    updateBean.setWebInterface(jsonObject.getString("webInterface"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                new Thread() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        UpdateManager manager = new UpdateManager(getActivity(), updateBean);
                        // 检查软件更新
                        manager.checkUpdate();
                        Looper.loop();
                    }
                }.start();
            } else {
                DialogHelper.showToast(getActivity(), JsonUtil.GetString(result, "msg"));
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            DialogHelper.showIOSProgressDialog("正在获取最新版本信息....", getActivity());
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            DialogHelper.closeIOSProgressDialog();
        }
    }
}
